package com.kbt.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.google.gson.Gson;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.listener.ClickActStartActForResultListener;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.YZCodeBeans;
import com.kbt.net.RequestManager;
import com.kbt.service.LoginService;
import com.kbt.simcpux.MD5Util;
import com.kbt.util.data.StaticData;
import com.kbt.util.tool.BtnSetting;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.MD5Utils;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author zhgk
 * @package: com.kbt.activity
 * @TODO: 登录Activity
 * @data: 2015/8/15 13:54
 * @version: V1.0
 */
public class LoginActivity extends Activity implements RequestManager.ResponseInterface{

    private BaseBean baseBean;
    private RequestManager mRequestManager;
    private Map<String,String> postMap=null;
    private String userName;
    private String passWord;
    private SharePreferenceUtils share;
    private LoadingDialog mProgress;

    /*********
     * 接收返回的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /***
     * @param savedInstanceState
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.login_layout);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不创建地址
                setResult(RESULT_CANCELED, null);
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("登录");
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        postMap = new HashMap<String, String>();
        share = new SharePreferenceUtils(LoginActivity.this);

    }

    /**
     * 重写启动方法
     */
    @Override
    protected void onStart() {

        super.onStart();
        //初始化登录列表
        initLoginView();
    }

    /***
     * 初始化登录
     */
    private void initLoginView() {

       final EditText userNameEdit = (EditText) findViewById(R.id.et_login_username);
        final EditText passWordEdit = (EditText) findViewById(R.id.et_password);
        Button loginBtn = (Button) findViewById(R.id.btn_login);
      final  TextView forgotPassWord = (TextView) findViewById(R.id.btn_findpass);
       final TextView registerNow = (TextView) findViewById(R.id.btn_regist);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName = userNameEdit.getText().toString().trim();
                passWord = passWordEdit.getText().toString().trim();
                if (userName.length() == 0) {
                    Toast.makeText(LoginActivity.this, "请输入手机号码!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passWord.length() == 0) {
                    Toast.makeText(LoginActivity.this, "请输入密码!", Toast.LENGTH_SHORT).show();
                    return;
                }
                String Md5Password = MD5Utils.Md5(passWord);
                //登录
                httpLogin(userName,Md5Password);
            }
        });
        /***
         * 忘记密码事件
         *
         * **/
        ClickActStartActForResultListener actListener = new ClickActStartActForResultListener(this,
                ForgotPassWordActivity.class, StaticData.LOGIN_FOR_FORGOT_PASS, null);
        forgotPassWord.setOnClickListener(actListener);

        /***
         * 立即注册事件
         */
        registerNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, LoginRegisterActivity.class);
                startActivity(intent);
//                finish();
            }
        });
    }
    //登录
    private void httpLogin(String userName,String passWord){
        showProgress();
        if(Utils.isNetworkAvailable(LoginActivity.this)) {
            postMap.clear();
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            postMap.put("user_mobile", userName);
            postMap.put("password", passWord);
            dataMap.put("data", gson.toJson(postMap));
            mRequestManager.post(Constants.ServiceInterFace.loginURL, dataMap, Constants.RequestTag.loginTag, BaseBean.class);
        }else{
            Toast.makeText(LoginActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //把服务器的数据存到share中 方便后面开发使用
    private void KeepUserDate(String userName,String passWord,String user_key){
        //将用户名（手机号）保存
        share.put("user_mobile",userName);
        share.put("password", passWord);
        share.put("user_key", user_key);
        finish();
    }
    //初始化极光推送
    private void jush(String userName){
        JPushInterface.setAlias(getApplicationContext(),
                userName, mTagsCallback);
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.loginTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    KeepUserDate(userName, passWord, baseBean.getUser_key());
                    jush(userName);
                }else{
                    Toast.makeText(LoginActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
        Toast.makeText(LoginActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(LoginActivity.this,"");
            mProgress.setCancelable(true);
            mProgress.show();

        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
            }

        }

    };
}
